package com.sfx.distributeLockStock.dao.mapper;

import com.sfx.distributeLockStock.dao.po.StockPO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-11-19
 * Time: 11:30
 */
@Mapper
public interface IStockMapper {

    @Select("select * from goods_stock")
    List<StockPO> selectAll();

    /**
     * 根据商品id查询库存信息
     *
     * @param goodsId 商品 id
     * @return 返回库存信息
     */
    @Select("select stock from goods_stock where goods_id = #{goodsId}")
    Integer selectStockByGoodsId(@Param("goodsId") Integer goodsId);



    /**
     * 更新库存
     *
     * @param goodsId 商品id
     * @param stock   扣减之后的库存
     */
    @Update("update goods_stock set stock = #{stock} where goods_id = #{goodsId}")
    Integer updateStockByGoodsId(@Param("goodsId") Integer goodsId, @Param("stock") Integer stock);



    /**
     * 悲观锁(单条update解决库存超卖问题)
     *
     * @param goodsId
     * @param count
     * @return
     */
    @Update("update goods_stock set stock = stock - #{count} where goods_id = #{goodsId} and stock >= #{count}")
    Integer updateStockByGoodsIdUpdate(@Param("goodsId")Integer goodsId, @Param("count") Integer count);



    /**
     * for update 解决悲观
     *
     * @param goodsId
     * @return

    */
    @Select("select stock from goods_stock where goods_id = #{goodsId} for update")
    Integer selectStockByGoodsIdForUpdate(@Param("goodsId") Integer goodsId);




    @Update("update goods_stock set stock = #{stock} , version = #{version} + 1 where goods_id = #{goodsId}" +
            " and version = #{version}")
    Integer updateStockByGoodsIdCAS(Integer goodsId, Integer stock, int version);


    @Select("select * from goods_stock where goods_id = #{goodsId} limit 1")
    StockPO selectStockByGoodsIdOne(Integer goodsId);
}